import React from 'react';
import {
	Button,
	Group,
	TextField,
	TextareaField,
	Toast,
	SelectField,
	SwitchField,
	Dialog,
} from 'saltui';
const {
	Count
} = TextareaField;
import PageController from 'pages/home';
import {
	urlPrefix,
	URLS,
	nodataIcon,
	dictMap
} from '../../../app/variables';
import DB from '../../../app/db';
import './PageHome.less';

import Util from 'components/common/util';
import Upload from 'components/upload';

export default class PageHome extends React.Component {

	constructor(props) { 
		super(props);		
		this.postId = props.params.postId;
		let isAuthor = props.params.isAuthor;
		this.checkStatus = props.params.checkStatus;
		let _boardReadOnly = this.postId == undefined || this.postId == "" ? false : true;
		let _publishTypeReadOnly = this.postId == undefined || this.postId == "" ? false : true;
		this.state = {
			boardIsAnonymity:0,
			boardIsPetname:0,
			isAuthor:isAuthor,
			isAnonymity:0,
			isPetname:0,
			picReadOnly: '',
			buttonAble:false,
			pagetype:props.params.pagetype,
			boardReadOnly:_boardReadOnly,
			isCopy: 1,
			isRePost: 1,
			isEditPost: 1,
			publishTypeReadOnly:_publishTypeReadOnly,
			form: {
				id: this.postId,
				checkStatus:this.checkStatus,
				title: '',
				content: '',
				board:null,
				attId: '',
				attIdJson:[],
				publishType:null,
			},
			anonymity:{},
			petname:{},
			boradArray: [],
			publishArray:[{"text":"主题","value": "1"}],
		}



		if(props.params.postId==undefined || props.params.postId==""){
			dd.biz.navigation.setTitle({
      		title: '新建',
		    onSuccess: function (result) {
		    },
     		 onFail: function () {
      		}
    		});
		}else{
			dd.biz.navigation.setTitle({
      		title: '编辑',
		    onSuccess: function (result) {
		    },
     		 onFail: function () {
      		}
    		});
		}
		

	}

	componentWillMount() {
		// debugger;
		this.postBoards();
	}

	componentDidMount() {
		
	}

	viewPost() {
		let t = this;
		DB.ForumModuleAPI.infoPost({
			id: this.postId,
			checkStatus: this.checkStatus
		}).then((content) => {
			let _ReadOnly = false;
			if(t.state.pagetype == "board"){
				if(content.isEditPost == '0'){
					_ReadOnly = true;
				}else{
					if(content.isAuthor==false){
						_ReadOnly = true;
					}else{
						_ReadOnly = false;
					}
				}
			}
			//我的草稿的所有帖子都可以重新编辑版块
			let boardIfReadOnly = (content.boardIsDelete && content.boardStatus=='1' && content.typeStatus=='1' )?true:false ;
			if(t.state.pagetype == "draft"){
				boardIfReadOnly = false;
			}
			var pstArray = [];
			if(content.publistType == '2'){
				pstArray = [{"text":"主题","value": "1"},{"text":"公告","value":"2"}]
			}else if(content.publistType == '1'){
				pstArray = [{"text":"主题","value": "1"}]
			}
			t.setState({
				publishArray:pstArray,
				boardIsAnonymity:content.boardIsAnonymity,
				boardIsPetname:content.boardIsPetname,
				isAnonymity:content.isAnonymity,
				isPetname:content.isPetname,
				isCopy: content.isCopy,
			    isRePost: content.isRePost,
				isEditPost: content.isEditPost,
				boardIsDelete: content.boardIsDelete,
				boardStatus:content.boardStatus,
				boardReadOnly: boardIfReadOnly,
				form: {
					id: content.id,
					checkStatus:content.checkStatus,
					title: content.title,
					content: content.content,
					board:(content.boardIsDelete && content.boardStatus=='1' && content.typeStatus=='1')?content.board:null,
					publishType:content.publishType,
					attId: content.attId,
					attIdJson:content.attIdJson,
				},
				ReadOnly:_ReadOnly
			},function(){
				t.refs.upload.initData();
			});
		}).catch((error) => {

		});
		
	}

	/**
	 * 获取当前用户可以发表帖子的版块
	 * @return {[type]}
	 */
	postBoards() {
		DB.ForumModuleAPI.postBoards().then((content) => {
			Toast.hide(); 
			if (content.content && content.content.length > 0) {
				let contentArray = content.content;
				let array = [];
				let _anonymity = {};
				let _petname = {};
				contentArray.map((item, index) => {
					let i = {
						text: item.name,
						value: item.id				
					}
					array.push(i);
					_anonymity[item.id] = item.boardIsAnonymity;
					_petname[item.id] = item.boardIsPetname;
				}); 
				this.setState({					
					boradArray: array,
					anonymity: _anonymity,
					petname: _petname,
					isAdminRole:content.isAdminRole
				},()=>{
					if (this.postId) {
						this.viewPost();
					}
				});
				
			}
		}).catch((error) => {
				
		});
	}

	/**
	 * 表单值修改公共方法
	 * @param  {[type]}
	 * @param  {[type]}
	 * @return {[type]}
	 */
	handleChange(field,field2, value) {	
		let form = this.state.form;
		if(field == 'board'){
			form[field] = value;
			let _anonymity = this.state.anonymity;
			let _petname = this.state.petname;
			let _isAnonymity = _anonymity[value.value];
			let _isPetname = _petname[value.value];
			//所选板块是否可以发布公告帖
			let array = [];
			let i ={
				"text":"主题",
				"value":"1"
			}
			let j = {
				"text":"公告",
				"value":"2"
			}
			DB.ForumModuleAPI.ifPost({
				boardId: value.value
				}).then((content) => {
				    if(content.ifAdminOrModerator == true){
				  	    array.push(i);
					    array.push(j);
				    }else{
					    array.push(i);
					}
				}).catch((error) => {
				Toast.show({
					type: 'error',
					content: '判断是否是管理员或版主出错'
				});
			})
			form[field2] = null,
			this.setState({
				boardIsAnonymity : _isAnonymity,
				boardIsPetname : _isPetname,
				form,
				publishArray : array,
			});
		}else{
			let form = this.state.form;
			form[field] = value;
			this.setState({
				form
			});
		}	
		
	}

handleChangePic(field,img){
   	 var id = "";
   	 var attId="attId";
    let form = this.state.form;
    //回显
    form[field]  = img;
    //取出图片ID赋值
	    if( img.length>0){
		    for(var i=0; i<img.length;i++){
		       id = id+img[i].id+'|';
	    }      
          id=id.substring(0,id.length-1);
         }
    form[attId]  = id;
   this.setState({
			form
		});
  }
	


	/**
	 * 多行文件值改变事件， 支持字符长度判断
	 * @param  {[type]} field    [description]
	 * @param  {[type]} size     [description]
	 * @param  {[type]} newValue [description]
	 * @return {[type]}          [description]
	 */
	handleTextAreaChange(field, size, newValue) {
		if (newValue.length <= size) {
			let form = this.state.form;
			form[field] = newValue;
			this.setState({
				form
			});
		}
	}

	/**
	 * 表单提交
	 * @return {[type]}
	 */
	saveSubmit(saveType){
		this.setState({
			buttonAble:true
		},()=>{

			this.handleSubmit(saveType);
			
		})
	}

	handleSubmit(saveType) {
		if(this.state.form.board==undefined || this.state.form.board==""){
        Toast.show({
          type: 'error',
          content: '请选择所属版块',
          onHide: function () {}
        });
        this.setState({
        	buttonAble:false
        })
      return false;
        
	  }

	if(this.state.form.publishType==undefined || this.state.form.publishType==""){
        Toast.show({
          type: 'error',
          content: '请选择发布类型',
          onHide: function () {}
        });
        this.setState({
        	buttonAble:false
        })
      return false;
        
      }
	if(this.state.form.title==undefined||this.state.form.title.trim()=="" ){
        Toast.show({
          type: 'error',
          content: '标题不能为空',
          onHide: function () {}
        });
        this.setState({
        	buttonAble:false
        })
      return false;
	  }
    if(isEmojiCharacter(this.state.form.title)){
        Toast.show({
        type: 'error',
        content: '标题不能输入表情',
        onHide: function () {}
     });
		this.setState({
			buttonAble:false
		})
		return false;
    }
	if(this.state.form.content==undefined || this.state.form.content.trim().replace(/\s+/g,"")==""){
        Toast.show({
          type: 'error',
          content: '内容不能为空',
          onHide: function () {}
        });
       this.setState({
        	buttonAble:false
        })
      return false;
      }
    if(isEmojiCharacter(this.state.form.content)){
        Toast.show({
        type: 'error',
        content: '内容不能输入表情',
        onHide: function () {}
        });
	    this.setState({
		   buttonAble:false
	     })
     return false;
	}
	  //所选板块是否在黑名单里面
	  DB.ForumModuleAPI.ifPost({
		boardId: this.state.form.board.value
	  }).then((content) => {
		if(content.ifPost =="true"){
			this.savePost(saveType);
		}else{
			Dialog.alert({
				title: '发帖',
				content: '无发帖权限，请联系版主',
			  });
			  this.setState({
				buttonAble:false
			})
		  return false;
		}
	  }).catch((error) => {
		Toast.show({
			type: 'error',
			content: '判断是否发帖出错'
		});
	  })
	}

	savePost(saveType){
		let entity = {
			id:this.state.form.id,
			boardId: this.state.form.board.value,
			pagetype:this.state.pagetype,
			author: this.props.params.author,
			title: this.state.form.title,
			attId: this.state.form.attId,
			content: this.state.form.content,
			type: 1,
			pagetype:this.state.pagetype,
			checkStatus:saveType,
			isAnonymity:this.state.isAnonymity,
			isPetname:this.state.isPetname,
			//isCopy: this.postId == undefined || this.postId == "" ? "1": this.state.isCopy,
			//isRePost: this.postId == undefined || this.postId == "" ? "1":  this.state.isRePost,
			//isEditPost: this.postId == undefined || this.postId == "" ? "1":  this.state.isEditPost,
			
			isCopy: this.state.isCopy,
			isRePost:  this.state.isRePost,
			isEditPost:  this.state.isEditPost,
		};

	
		DB.ForumModuleAPI.editPost({
			entity: JSON.stringify(entity),
			publistType:this.state.form.publishType.value,
			pagetypes:this.state.pagetype,
			ids:this.state.form.id,
		}).then((content) => {
			Toast.hide();
			if(content.checkStatus == '1'){
				if(this.state.form.publishType.value == 1){
					Dialog.alert({
					  title: '发布',
					  content: '发布成功，您的帖子需要通过审核才能显示',
					  onConfirm() {
							history.go(-1);
							//location.hash = "#/post/editView/" + content.id + '/' + content.checkStatus + '/' + content.isModerator + '/' + content.author + '/' + content.isAuthor + '/1';
					  },
					});
				}else{
					Dialog.alert({
						title: '发布',
						content: '发布成功',
						onConfirm() {
							  history.go(-1);
							  //location.hash = "#/post/editView/" + content.id + '/' + content.checkStatus + '/' + content.isModerator + '/' + content.author + '/' + content.isAuthor + '/1';
						},
					  });
				}
			}else if(content.checkStatus == '4'){
				if(this.state.form.publishType.value == 1){
					Dialog.alert({
					  title: '发布',
					  content: '发布成功',
					  onConfirm() {
							history.go(-1);
						   //location.hash = "#/post/editView/" + content.id + '/' + content.checkStatus + '/' + content.isModerator + '/' + content.author + '/' + content.isAuthor + '/1';
					  },
					});
				}else{
					Dialog.alert({
						title: '发布',
						content: '发布成功',
						onConfirm() {
							  history.go(-1);
							  //location.hash = "#/post/editView/" + content.id + '/' + content.checkStatus + '/' + content.isModerator + '/' + content.author + '/' + content.isAuthor + '/1';
						},
					  });
				}
			}else if(content.checkStatus == '0'){
				Toast.show({
					type: 'success',
					content: '保存成功'
				});
				
				setTimeout(function(){
						history.go(-1);
					},200);
				//window.salt.router.goBack();
				/*if(this.state.form.checkStatus=='0'){
					history.go(-1);
				}else{
					setTimeout(function(){
						location.hash = "#/my/page/4";
					},200);
					//history.go(-1);
					if(this.state.form.id==undefined || this.state.form.id==""){
						backPage();
					}
				}*/
				
				
			}
			//window.salt.router.goBack();
		}).catch((error) => {
			this.setState({
				buttonAble:false
			},()=>{
				if (typeof(error.errorMsg) == 'undefined') {
				Toast.show({
					type: 'error',
					content: '发帖出错'
				});
			} else {
				Toast.show({
					type: 'error',
					content: error.errorMsg
				});
			}
			})
			
		});
	}


	

	/**
	 * 取消提交表单
	 * @return {[type]}
	 */
	handleSave() {
		this.saveSubmit("0");
	}

	handleChangeAnonymity(value) {
		if(value){
			value = "1";
			this.setState({
				isPetname: '0',
			});
		}else{
			value = "0";
		}
	    this.setState({
	      isAnonymity: value,
	    });
	}

	handleChangePetname(value) {
		DB.ForumModuleAPI.ifPetname({
			}).then((content) => {
				if(content.petName == ''){
					this.setState({
						isPetname: '0',
					});
					Toast.show({
						type: 'error',
						content: '您的昵称为空，不可选择昵称发帖方式'
					});
				}else{
					if(value){
						value = "1";
						this.setState({
							isAnonymity: '0',
						});
					}else{
						value = "0";
					}
					this.setState({
					  isPetname: value,
					});
				}
			}).catch((error) => {
				Toast.show({
					type: 'error',
					content: '获取昵称出错'
				});
		})
	}

	handleChangeCopy(value) {
		let isRePost = this.state.isRePost;
		let isEditPost = this.state.isEditPost;
		if(value){
			value = "1";
		}else{
			value = "0";
		}
	    this.setState({
			isRePost : isRePost,
			isCopy: value,
			isEditPost: isEditPost,
		});
	}

	handleChangeRePost(value) {
		let isEditPost = this.state.isEditPost;
		let isCopy = this.state.isCopy;
		if(value){
			value = "1";
		}else{
			value = "0";
		}
	    this.setState({
			isRePost: value,
			isCopy: isCopy,
			isEditPost: isEditPost,
	    });
	}

	handleChangeEditPost(value) {
		let isRePost = this.state.isRePost;
		let isCopy = this.state.isCopy;
		if(value){
			value = "1";
		}else{
			value = "0";
		}
	    this.setState({
			isRePost: isRePost,
			isCopy: isCopy,
			isEditPost: value,
	    });
	}

	render() {
		let t = this; 
			return(
				<div className="page-add">
						<Group>
							<Group.List >
								<SelectField
									required
									label="所属版块"
									placeholder="请选择"
									options={this.state.boradArray}
									readOnly={this.state.boardReadOnly} 
									onSelect={(value) => {this.handleChange('board','publishType', value); }}
									value={this.state.form.board}
								/>
							</Group.List>
							<Group.List >
								<SelectField
									required
									label="发布类型"
									placeholder="请选择"
									options={this.state.publishArray}
									readOnly={this.state.boardReadOnly} 
									onSelect={(value) => {this.handleChange('publishType','publishType', value); }}
									value={this.state.form.publishType}
								/>
							</Group.List>
							<Group.List >
								<TextareaField
									required
									readOnly={this.state.ReadOnly}
									label="标题"
									minRows={2} maxRows={3}
									placeholder="1-30个字符"
									value={this.state.form.title}
									onChange={this.handleTextAreaChange.bind(this, 'title', 30)} >
									{/* <Count total={30} length={this.state.form.title.length} /> */}
								</TextareaField>
							</Group.List>
							<Group.List >
						    <ol>
								<TextareaField
									className="text-edit"	           
									required
									label="内容"
									readOnly={this.state.ReadOnly}
									layout="v"
									minRows={8} maxRows={11}
									placeholder="请输入..."
									value={this.state.form.content}
									onChange={this.handleTextAreaChange.bind(this, 'content', 5000)} >
									<Count total={5000} length={this.state.form.content.length} />
								</TextareaField>
							</ol>
							</Group.List>	
							<Group.List  className="t-PB16">
							<Upload 
								uploadType="image"
								extensions='jpg,jpeg,png,gif,webp,bmp'
								label="图片"
								initList={this.state.form.attIdJson} 
								dir="forum" 
								canAdd={true}
								canDel={true} 
								onChange={this.handleChangePic.bind(this,'attIdJson')} 
								onDel={this.handleChangePic.bind(this,'attIdJson')}
								//canAdd="false" canDel="false" limitNo="9"
								limitNo="9"
								fileSizeLimit="10"
								ref="upload"
								/>
							</Group.List>
					<Group.List className={t.state.boardIsAnonymity == 1 ? "" : "t-DN"}> 
										<SwitchField
											label="是否匿名"
											on={t.state.isAnonymity == 1 ? true : false}
											onChange={t.handleChangeAnonymity.bind(this)}
										/>
									 </Group.List>
									 <Group.List className={t.state.boardIsPetname == 1 ? "" : "t-DN"}> 
										<SwitchField
											label="是否昵称"
											on={t.state.isPetname == 1 ? true : false}
											onChange={t.handleChangePetname.bind(this)}
										/>
									 </Group.List>
					<Group.List className={t.state.isAdminRole == true ? "" : "t-DN"}> 
										<SwitchField
											label="允许复制"
											on={t.state.isCopy == 1 || t.state.isCopy=='' ? true : false}
											onChange={t.handleChangeCopy.bind(this)}
										/>
									 </Group.List>
					<Group.List className={t.state.isAdminRole == true ? "" : "t-DN"}> 
										<SwitchField
											label="允许跟帖"
											on={t.state.isRePost == 1 || t.state.isRePost==''  ? true : false}
											onChange={t.handleChangeRePost.bind(this)}
										/>
									 </Group.List>
					<Group.List className={t.state.isAdminRole == true ? "" : "t-DN"}> 
										<SwitchField
											label="允许修改"
											on={t.state.isEditPost == 1 || t.state.isEditPost==''  ? true : false}
											onChange={t.handleChangeEditPost.bind(this)}
										/>
									 </Group.List>
					</Group>
						<div>
							<Button.Group className="page-add">					
							<Button className={(this.state.form.checkStatus=='0'||this.state.form.checkStatus==undefined||this.state.form.checkStatus==''
								        )?"":"t-DN"} disabled={this.state.buttonAble} type="secondary" display="inline" onClick={this.handleSave.bind(this)}>存草稿</Button>				
								<Button type="primary" display="inline" disabled={this.state.buttonAble}
											 onClick={this.saveSubmit.bind(this,"1")}>发布</Button>	  
							</Button.Group>
						</div>		
					</div>	
			);
	
	}
}